#include "StarburstCommon.h"
#include <EEPROM.h>

unsigned long dataStartTime;
unsigned long refreshCount;


float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
	return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}



uint8_t audioBreak[5] = {0, 0,1,0,1};
void initRadio(RF24 radio, bool reading) {
	radio.begin();
	radio.setDataRate(RF24_2MBPS);
	radio.enableDynamicPayloads();
	radio.enableNoAck();
	if(reading) {
		radio.openReadingPipe(0,PIPE1);
		radio.openWritingPipe(PIPE2);
	}
	else {
		radio.openWritingPipe(PIPE1);
		radio.openReadingPipe(1,PIPE2);
	}

	radio.startListening();
}



uint16_t readInt16FromEEprom(int wordAddress) {
	wordAddress *= 2;
	return (EEPROM.read(wordAddress) << 8) | EEPROM.read(wordAddress + 1);
}

void writeInt16ToEEPRom(int wordAddress, uint16_t value) {
	wordAddress *= 2;
	EEPROM.write(wordAddress,(value & 0xFF00) >> 8);
	EEPROM.write(wordAddress + 1, (value & 0xFF));
}



void drawAudioData(LegData *audioData, RGB *buffer, float hueShift, uint8_t saturation, uint8_t dimV, uint8_t brightV) {
	int v;
	for(int i = 0; i < 8; i++) {
		uint8_t hue = bucketColor(i,hueShift);
		RGB bc = LEDFxUtilities::HSVtoRGB(hue,saturation,brightV);
		RGB dc = LEDFxUtilities::HSVtoRGB(hue,saturation,dimV);

		int offset = i*16;
		bool fading = true;
		for(int j = 0; j < 16; j++) {
			int pixel1 = offset + j;
			if(j < audioData[i].value) {
				buffer[pixel1] = bc;
			}
			else {
				RGB rgb = buffer[pixel1];
				v = max(max(rgb.r,rgb.g),rgb.b);
				if(fading) {
					buffer[pixel1] = LEDFxUtilities::HSVtoRGB(hue,saturation,max(v-FADE_RATE, dimV));
					if(v-FADE_RATE <= dimV)
						fading = false;
				}
				else
					buffer[pixel1] = dc;
			}
		}
		memcpy(&buffer[((LEG_COUNT-1)-i)*BUCKET_SIZE],&buffer[offset],BUCKET_SIZE*sizeof(struct RGB));
	}
}



uint8_t bucketColor(int bucketNum, float colorShift) { 
	float v = ((float)bucketNum/((float)MIRRORED_LEGS))+colorShift;
	if(v >= 1.0)
		v -= 1.0;
	return v*255;
}